
package com.century.sjt.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.AddressAddActivity;
import com.century.sjt.entity.Address;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import android.widget.ImageView;
//import com.century.sjt.activity.Merchant.MerchantItemActivity;

/**
 * 地址
 */
public class AddressAdapter extends BaseAdapter {

    private LayoutInflater mLayoutInflater;
    private List<Address> mDataList = new ArrayList<>();
    private Context context;
    private RequestQueue mQueue;
    //初始化
    public AddressAdapter(Context context, List<Address> aList, RequestQueue mQueue) {
        this.mDataList = aList;
        this.context = context;
        mLayoutInflater = LayoutInflater.from(context);
        this.mQueue = mQueue;
    }



    @Override
    public int getCount() {
        return mDataList.size();
    }

    @Override
    public Object getItem(int i) {
        return mDataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View convertView, ViewGroup viewGroup) {

        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.adapter_address_item, null);
            holder.tvAddress = (TextView) convertView.findViewById(R.id.item_tv_address);
            holder.tvName = (TextView) convertView.findViewById(R.id.item_tv_name);
            holder.tvPhome = (TextView) convertView.findViewById(R.id.item_tv_phome);
            holder.layout_delect = (LinearLayout) convertView.findViewById(R.id.item_layout_delete);
            holder.layout_edit = (LinearLayout) convertView.findViewById(R.id.item_layout_edit);
//            holder.checkBox = (CheckBox) convertView.findViewById(R.id.item_check);
            holder.layout_setCheck = (LinearLayout) convertView.findViewById(R.id.item_layout_setcheck);
            holder.tvCheck = (TextView) convertView.findViewById(R.id.item_check_text);
            holder.icon_trash = (TextView) convertView.findViewById(R.id.icon_trash);
            holder.icon_write = (TextView) convertView.findViewById(R.id.icon_write);
            holder.unselected = (TextView) convertView.findViewById(R.id.icon_unselected);
            Typeface iconfont = Typeface.createFromAsset(context.getAssets(), "iconfont.ttf");
            holder.icon_write.setTypeface(iconfont);
            holder.icon_trash.setTypeface(iconfont);
            holder.unselected.setTypeface(iconfont);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (mDataList.get(i).getIsDefault().equals("1")) {
            holder.unselected.setText(context.getResources().getString(R.string.icon_select2));
            holder.tvCheck.setText(context.getResources().getString(R.string.text_address_default));
//            holder.tvCheck.setTextColor(context.getResources().getColor(R.color.textdefault_orange));
        } else {
            holder.unselected.setText(context.getResources().getString(R.string.icon_unselected));
            holder.tvCheck.setText(context.getResources().getString(R.string.text_set_default));
//            holder.tvCheck.setTextColor(context.getResources().getColor(R.color.textdefault_textgrey));
        }


        holder.layout_setCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defaultReceiver(mDataList.get(i).getSysId());

            }
        });
        holder.tvAddress.setText(mDataList.get(i).getAddress());
        holder.tvPhome.setText(mDataList.get(i).getPhone());
        holder.tvName.setText(mDataList.get(i).getConsignee());
        holder.layout_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(context, AddressAddActivity.class);
                Bundle mBundle = new Bundle();
                Address address = mDataList.get(i);
                mBundle.putSerializable("address", address);
                intent.putExtras(mBundle);
                intent.putExtra("Type", "1");
                context.startActivity(intent);
            }
        });
        holder.layout_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAppayRes(mDataList.get(i).getSysId());

            }
        });
        return convertView;

    }

    class ViewHolder {
        public TextView tvAddress;
        public TextView tvName;
        public TextView tvPhome;
//        public CheckBox checkBox;
        public TextView tvCheck;
        public LinearLayout layout_edit;
        public LinearLayout layout_delect;
        public LinearLayout layout_setCheck;
        public TextView icon_write;
        public TextView icon_trash;
        public TextView unselected;

    }

    private void delectAddress(final String sysId) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, context.getResources().getString(R.string.error_please_waitting), context);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.delectAddress, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取地址", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        getAddress();
                        TipUtil.showToast(context.getResources().getString(R.string.error_delete_success), context, 1);

                    } else {//失败
                        TipUtil.showToast(message, context, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(context.getResources().getString(R.string.error_service), context, 1);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(context.getResources().getString(R.string.error_network), context, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("sysId", sysId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    private void getAddress() {
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.queryReceiver, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取地址", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONArray data = res.getJSONArray("data");
                        mDataList.clear();
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject aData = (JSONObject) data.get(i);
//
                            Address address = new Address();
                            address.setSysId(aData.getString("sysId"));
                            address.setAddress(aData.getString("address"));
                            address.setAreaName(aData.getString("areaName"));
                            address.setConsignee(aData.getString("consignee"));
                            address.setIsDefault(aData.getString("isDefault"));
                            address.setPhone(aData.getString("phone"));
                            address.setIpCode(aData.getString("zipCode"));
                            address.setArexz(aData.getString("areaName"));
                            address.setUserId(aData.getString("userId"));
                            mDataList.add(address);
                        }
                    } else {//失败
                        TipUtil.showToast(message, context, 1);
                    }
                    notifyDataSetChanged();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(context.getResources().getString(R.string.error_service), context, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(context.getResources().getString(R.string.error_network), context, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
//                map.put("paging.currentPage",String.valueOf(iCurrPage));//当前页码
//                map.put("paging.pageSize",Constant.PAGESIZE+" ");//查询条数

                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }


    private void defaultReceiver(final String sysId) {
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,context. getResources().getString(R.string.please_waitting), context);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.defaultReceiver, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("设置默认地址返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        getAddress();
//                        TipUtil.showToast("默认地址变更成功", context, 1);

                    } else {//失败
                        TipUtil.showToast(message, context, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(context.getResources().getString(R.string.error_service), context, 1);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(context.getResources().getString(R.string.error_network), context, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("sysId", sysId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    public void showAppayRes(final String id) {
        //询问是否取消
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(context.getResources().getString(R.string.text_prompt));
        builder.setMessage(context.getResources().getString(R.string.error_is_delete_address));
        builder.setPositiveButton(context.getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                delectAddress(id);

            }
        });
        builder.setNegativeButton(context.getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }
}
